
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
	
	private String path;//加载类的路径
	private String name;//
	
	
	
	public MyClassLoader(String path, String name) {
		super();//让系统类加载器为该类的父加载器
		this.path = path;
		this.name = name;
	}
	
	public MyClassLoader(ClassLoader parent, String path, String name) {
		super(parent);//显式指定父加载器
		this.path = path;
		this.name = name;
	}


	/**
	 * 
	 */
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
			
		byte[] data = readClassFileToByteArray(name);
		return this.defineClass(name, data, 0, data.length);
		
	}


	/**
	 * 获取.class文件的字节数组
	 * @param name2
	 * @return
	 */
	private byte[] readClassFileToByteArray(String name2) {
		InputStream is = null;
		byte[] returnData = null;
		
		name2 = name2.replace(".", "//");//("\\.", "/")
		
		String filePath = this.path + name2 + ".class";
		File file = new File(filePath);
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			is = new FileInputStream(file);
			int tmp = 0;
			while((tmp = is.read()) != -1) {
				os.write(tmp);
			}
			returnData = os.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		return returnData;
	}

}
